package thread.synchronized_;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-03-07
 * Time:19:09
 */
public class CodeBlock {
    public static void main(String[] args) {
//        M3 m3 = new M3();
        for (int i = 0; i < 5; i++) {
            M3 m3 = new M3();
            new Thread(m3).start();
        }
    }
}

class M3 implements Runnable {
    @Override
    public void run() {
        func1();
        func2();
        Integer num = 1;
        func3(num);
        func4();
    }

    public void func1() {
        synchronized (this) {//代码块,锁定的是调用者,即M3的实例化对象
            System.out.println("start1...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("end1.....");
        }
    }

    public void func2() {
        String s = "hello";
        synchronized (s) {//代码块,锁定的是s,即s对象(常量池对象一致)
            System.out.println("start2.....");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("end2.......");
        }
    }

    public void func3(Integer num) {
        synchronized (num) {//代码块,锁定的是传入对象,Integer num对象
            System.out.println("........start3");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("..........end3");
        }
    }

    public void func4() {
        synchronized (M3.class) {//代码块,锁定的是M3类
            System.out.println("...........start4");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("..........end4");
        }
    }
}
